2
2
.
.
1
1
1
1
.
.
9
9
F
F
r
r
o
o
m
m
J
J
S
S
O
O
N
N
-
-
@
@
J
J
s
s
o
o
n
n
P
P
r
r
o
o
p
p
e
e
r
r
t
t
y
y
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
This tutorial shows how to use @JsonProperty Annotation to map Properties from JSON HTTP Request into DTO.
(You can also use it to map to Entity if you are not using DTO between Controller and Service Layer).
@JsonProperty Annotation can be used to
Annotate public Properties (when public Properties are used for Deserialization in absence of Constructor)
Annotate Constructor Parameters (when Constructor is used for Deserialization)
Syntax
@JsonProperty("First Name") //JSON PROPERTY
public String name; //DTO PROPERTY
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: @Controller @RequestMapping, Tomcat Server
MyController
PersonDTO
POSTMAN
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: bootspring_http_requestbody (add Spring Boot Starters from the table)
Create Package: DTO (inside main package)
Create Class: PersonDTO.java (inside package controllers)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
PersonDTO.java
package com.ivoronline.springboot_dto_jsonproperty.DTO;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PersonDTO {
//JSON PROPERTIES //DTO PROPERTIES
@JsonProperty("First Name") public String name; //Completely different name (and with space)
@JsonProperty("Age") public Integer age; //Uppercase A
}
MyController.java
package com.ivoronline.springboot_dto_jsonproperty.controllers;
import com.ivoronline.springboot_dto_jsonproperty.DTO.PersonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPerson")
public String addPerson(@RequestBody PersonDTO personDTO) {
//GET DATA FROM PersonDTO
String name = personDTO.name;
Integer age = personDTO.age;
//RETURN SOMETHING
return name + " is " + age + " years old";
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
Start Postman
POST
http://localhost:8080/AddPerson
Headers (add Key-Value)
Content-Type: application/json
Body (option: raw)
{
"First Name" : "John",
"Age" : 20
}
Postman
HTTP Response Body
John is 20 years old
Application Structure
pomx.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>